package org.elephas.service;

import java.util.Iterator;
import java.util.List;

import org.elephas.model.Blog;
import org.elephas.persistence.Dao;
import org.elephas.persistence.query.QueryParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
@SuppressWarnings({"unchecked"})
public class BlogFinder {

	@Autowired
	private Dao dao;

	/**
	 * @param param
	 * @return
	 */
	public List<Blog> findBlogs(QueryParam param) {
		return dao.createQuery("select blog from Blog blog", param).list();
	}

	/**
	 * @param param
	 * @return
	 */
	public Iterator<Blog> iterateBlogs(QueryParam param) {
		return dao.createQuery("from Blog blog", param).iterate();
	}

	/**
	 * Calculates the number of {@link Blog}s available.
	 * 
	 * @return the number of {@link Blog}s
	 */
	public int countBlogs() {
		Long count = (Long) dao
				.createQuery("select count(blog) from Blog blog")
				.uniqueResult();
		return count.intValue();
	}

	/**
	 * Loads a blog by its name.
	 * 
	 * @param name
	 *            the blog's name
	 * @return the blog with the specified name
	 * @throws BlogNotFoundException
	 *             in case no blog with the specified name was found
	 */
	public Blog findByName(String name) {
		Blog blog = (Blog) dao.createQuery(
				"from Blog blog where blog.name=:name").setParameter("name",
				name).uniqueResult();
		if (blog == null) {
			throw new BlogNotFoundException(name);
		}
		return blog;
	}

	/**
	 * Loads a blog by its uuid.
	 * 
	 * @param uuid
	 *            the blog's uuid
	 * @return the blog
	 * @throws BlogNotFoundException
	 *             in case no blog with the specified uuid exists
	 */
	public Blog findById(String uuid) {
		Blog blog = (Blog) dao.get(Blog.class, uuid);
		if (blog == null) {
			throw new BlogNotFoundException(uuid);
		}
		return blog;
	}
}
